package com.bamboo.mall.product.service.impl;

import com.bamboo.common.utils.PageUtils;
import com.bamboo.common.utils.Query;
import com.bamboo.mall.product.dao.CategoryDao;
import com.bamboo.mall.product.entity.CategoryEntity;
import com.bamboo.mall.product.entity.dto.category.CategoryDetailDTO;
import com.bamboo.mall.product.service.CategoryBrandRelationService;
import com.bamboo.mall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryDetailDTO> listWithTree() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        List<CategoryDetailDTO> level1List = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(categoryEntityList)) {
            List<CategoryDetailDTO> allList = categoryEntityList.stream().map(CategoryDetailDTO::convertFor).collect(Collectors.toList());

            level1List = allList.stream().filter(categoryDetailDTO ->
                    categoryDetailDTO.getParentCid() == 0L
            ).map((obj) -> {
                obj.setChildren(getChildren(obj, allList));
                return obj;
            }).sorted(Comparator.comparingInt(o -> (Objects.nonNull(o.getSort()) ? o.getSort() : 0)))
                    .collect(Collectors.toList());

        }

        return level1List;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO  1、检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Override
    public List<Long> findCatelogPath(Long catelogId) {
        List<Long> resultList = Lists.newArrayList();
        // Long[] result = paths.toArray(new Long[paths.size()]);
        findParentPath(catelogId, resultList);
        Collections.reverse(resultList);
        return resultList;
    }

    private void findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = getById(catelogId);
        if (Objects.nonNull(categoryEntity)) {
            Long parentCid = categoryEntity.getParentCid();
            if (Objects.nonNull(parentCid) && parentCid != 0L) {
                findParentPath(parentCid, paths);
            }
        }
    }

    private List<CategoryDetailDTO> getChildren(CategoryDetailDTO categoryDetailDTO, List<CategoryDetailDTO> list) {
        return list.stream().filter(obj -> obj.getParentCid().equals(categoryDetailDTO.getCatId()))
                .map((obj) -> {
                    obj.setChildren(getChildren(obj, list));
                    return obj;
                }).sorted(Comparator.comparingInt(o -> (Objects.nonNull(o.getSort()) ? o.getSort() : 0)))
                .collect(Collectors.toList());
    }
}